using System.Threading;

namespace Nice157Advices.Advices
{
    /// <summary>
    /// 建议75：警惕线程不会立即启动
    /// </summary>
    public static class _75
    {
        /**
         * 线程的调度是一个复杂的过程，对于C#开发者来说，需要理解的就是：线程之间的调度占有一定的时间和空间开销，并且，它不实时。
         */
        
        public static void Go ()
        {
            // Test1 ();

            Test2();    // 将for循环改成一段同步代码
        }

        private static void Test1 ()
        {
            int _id = 0;
            for (int i = 0; i < 10; i++, _id++)
            {
                Thread t = new Thread (() =>
                {
                    System.Console.WriteLine ($"{Thread.CurrentThread.Name}:{_id}");
                });
                t.Name = $"Thread{i}";
                // t.IsBackground = true;
                t.Start ();
            }
        }

        private static void Test2 ()
        {
            int _id = 0;
            for (int i = 0; i < 10; i++, _id++)
            {
                // 将for循环改成一段同步代码
                Method (i, _id);
            }
        }

        private static void Method (int i, int id)
        {
            Thread t = new Thread (() =>
            {
                System.Console.WriteLine ($"{Thread.CurrentThread.Name}:{id}");
            });
            t.Name = $"Thread{i}";
            // t.IsBackground = true;
            t.Start ();
        }
    }
}